package tree.traverse;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 二叉树前序遍历
 *
 * @author xushijian
 * @date 2021/08/02 16:18
 */
public class PreOrder {

    /**
     * 前序遍历 (根前，从左到右）
     *
     * @param treeNode 树
     * @return 遍历结果
     */
    public List<Integer> preOrder(TreeNode treeNode) {

        List<Integer> result = new ArrayList<Integer>();
        if (treeNode == null) {
            return result;
        }

        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(treeNode);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.right != null) {
                stack.push(node);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
            result.add(node.val);
        }

        return result;
    }

}